<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px" size="medium" class="ry_form">
      <el-form-item label="兑换码" prop="code">
        <el-input
          v-model.trim="queryParams.code"
          placeholder="请输入兑换码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
            <el-option
              v-for="dict in dict.type.codetype"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
        </el-select>
      </el-form-item>
      <template v-if="showMoreCondition">
      <el-form-item label="兑换用户ID" prop="usedUserId">
        <el-input
          v-model.trim="queryParams.usedUserId"
          placeholder="请输入兑换用户ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用时间" prop="usedTime">
        <el-date-picker
            clearable
            size="small"
            v-model="queryParams.usedTime"
            type="datetime"
            value-format="yyyy-MM-ddTHH:mm:ss"
            placeholder="选择使用时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker
            clearable
            size="small"
            v-model="queryParams.expireTime"
            type="datetime"
            value-format="yyyy-MM-ddTHH:mm:ss"
            placeholder="选择过期时间">
        </el-date-picker>
      </el-form-item>
    </template>
      <el-form-item class="flex_one tr">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="showMoreCondition ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" size="mini" @click="showMoreCondition = !showMoreCondition">{{showMoreCondition ? '收起条件' : '展开条件'}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['act:FhVipExchangeCode:add']"
        >生成兑换码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['act:FhVipExchangeCode:remove']"
        >删除</el-button>
      </el-col>
     
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="FhVipExchangeCodeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="兑换码" align="center" prop="code" v-if="columns[0].visible"/>
      <el-table-column label="VIP类型" align="center" prop="vipType" v-if="columns[1].visible"/>
      <el-table-column label="VIP天数" align="center" prop="vipDays" v-if="columns[2].visible"/>
      <el-table-column label="原价" align="center" prop="originalPrice" v-if="columns[3].visible"/>
      <el-table-column label="折扣价" align="center" prop="discountPrice" v-if="columns[4].visible"/>
      <el-table-column label="状态" align="center" prop="status" v-if="columns[5].visible">
        <template slot-scope="scope">
            <dict-tag :options="dict.type.codetype" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="兑换用户ID" align="center" prop="usedUserId" v-if="columns[6].visible"/>
      <el-table-column label="使用时间" align="center" prop="usedTime" width="180" v-if="columns[7].visible">
        <template slot-scope="scope">
            <span>{{ parseTime(scope.row.usedTime, '')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180" v-if="columns[8].visible">
        <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expireTime, '')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[9].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['act:FhVipExchangeCode:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改VIP兑换码表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="108px" inline class="dialog-form-two">
        <el-form-item label="VIP套餐" prop="rechargeDataId">
          <el-select v-model="form.rechargeDataId" placeholder="请选择VIP套餐" @change="onVipPackageChange">
            <el-option
              v-for="item in vipPackageList"
              :key="item.id"
              :label="`${item.type} - ${item.day}天 - ¥${item.discountPrice}`"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生成数量" prop="generateCount">
          <el-input-number v-model="form.generateCount" :min="1" :max="1000" placeholder="请输入生成数量" />
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker clearable size="small"
                        v-model="form.expireTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFhVipExchangeCode, getFhVipExchangeCode, delFhVipExchangeCode, addFhVipExchangeCode, updateFhVipExchangeCode, exportFhVipExchangeCode, batchGenerateVipExchangeCode } from "@/api/act/fhVipExchangeCode";
import { listFhRechargeData } from "@/api/act/fhRechargeData";
import { listVipConfig } from "@/api/vip/vipPayment";

export default {
  name: "FhVipExchangeCode",
  dicts: ['codetype'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // VIP兑换码表表格数据
      FhVipExchangeCodeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        rechargeDataId: null,
        vipType: null,
        vipDays: null,
        originalPrice: null,
        discountPrice: null,
        status: null,
        usedUserId: null,
        usedTime: null,
        expireTime: null,
      },
      // 表单参数
      form: {},
      // VIP套餐列表
      vipPackageList: [],
      // 表单校验
      rules: {
        rechargeDataId: [
          { required: true, message: "VIP套餐不能为空", trigger: "change" }
        ],
        generateCount: [
          { required: true, message: "生成数量不能为空", trigger: "blur" }
        ],
        expireTime: [
          { required: true, message: "过期时间不能为空", trigger: "blur" }
        ],
      },
      columns: [
            { key: 1, label: "兑换码", visible:  true  },
                { key: 3, label: "VIP类型", visible:  true  },
            { key: 4, label: "VIP天数", visible:  true  },
            { key: 5, label: "原价", visible:  true  },
            { key: 6, label: "折扣价", visible:  true  },
            { key: 7, label: "状态", visible:  true  },
            { key: 8, label: "兑换用户ID", visible:  true  },
            { key: 9, label: "使用时间", visible:  true  },
            { key: 10, label: "过期时间", visible:  false  },
                            { key: 15, label: "备注", visible:  false  },
         ],
      showMoreCondition: false
    };
  },
  created() {
    this.getList();
    this.getVipPackageList();
  },
  methods: {
    /** 查询VIP兑换码表列表 */
    getList() {
      this.loading = true;
      const {pageNum, pageSize} = this.queryParams;
      const query = {...this.queryParams, pageNum: undefined, pageSize: undefined};
      const pageReq = {page: pageNum - 1, size: pageSize};
      listFhVipExchangeCode(query, pageReq).then(response => {
        const { content, totalElements } = response
        this.FhVipExchangeCodeList = content;
        this.total = totalElements;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        rechargeDataId: null,
        generateCount: 1,
        expireTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "生成VIP兑换码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFhVipExchangeCode(id).then(response => {
        this.form = response;
        this.open = true;
        this.title = "修改VIP兑换码表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFhVipExchangeCode(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 批量生成兑换码
            const generateData = {
              rechargeDataId: this.form.rechargeDataId,
              count: this.form.generateCount,
              expireTime: this.form.expireTime,
              remark: this.form.remark
            };
            batchGenerateVipExchangeCode(generateData).then(response => {
              this.$modal.msgSuccess(`成功生成${this.form.generateCount}张兑换码`);
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除VIP兑换码表编号为"' + ids + '"的数据项？').then(function() {
        return delFhVipExchangeCode(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有VIP兑换码表数据项？').then(() => {
        this.exportLoading = true;
        return exportFhVipExchangeCode(queryParams);
      }).then(response => {
        this.$download.download(response);
        this.exportLoading = false;
      }).catch(() => {});
    },
    /** 获取VIP套餐列表 */
    getVipPackageList() {
      // 尝试从两个不同的接口获取VIP套餐数据
      listFhRechargeData({}, { page: 0, size: 1000 }).then(response => {
        if (response && response.content) {
          this.vipPackageList = response.content;
        }
      }).catch(() => {
        // 如果第一个接口失败，尝试第二个接口
        listVipConfig({}).then(response => {
          if (response && response.data) {
            this.vipPackageList = response.data;
          }
        }).catch(() => {
          this.$modal.msgError("获取VIP套餐列表失败");
        });
      });
    },
    /** VIP套餐选择变化 */
    onVipPackageChange(value) {
      const selectedPackage = this.vipPackageList.find(item => item.id === value);
      if (selectedPackage) {
        // 自动填充相关信息（如果需要显示的话）
        console.log('选中的VIP套餐:', selectedPackage);
      }
    }
  }
};
</script>
